package com.hikvision.ae.controller;

import com.hikvision.ae.common.AreaInfo;
import com.hikvision.ae.common.CommonResult;
import com.hikvision.ae.common.Gps;
import com.hikvision.ae.common.MassPoint;
import com.hikvision.ae.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author jinjinhui
 * @date 2020/5/14
 */
@RestController
public class BaseController {

    @Autowired
    private BaseService baseService;

    @RequestMapping("/upload")
    public CommonResult upload(
        @RequestParam(name = "file")
        MultipartFile multipartFile) {
        List<MassPoint> points = baseService.getPointsFromFile(multipartFile);
        return new CommonResult().success(points);
    }

    @RequestMapping(value = "/analysis")
    public CommonResult analysis(
        @RequestParam(name = "errorRange", defaultValue = "30")
        Integer errorRange){
        List<AreaInfo> points = baseService.analysis(errorRange);
        if(points == null){
            return new CommonResult().fail("alarm.analysis.excelNotUploaded", "请上传废弃斑马线报警文档");
        }
        return new CommonResult().success(points);
    }

    @RequestMapping("/isAnalysised")
    public CommonResult isAnalysised(){
        boolean isAnalysised = baseService.isAnalysised();
        if(isAnalysised){
            return new CommonResult().success();

        }
        return new CommonResult().fail("alarm.analysis.excelNotAnalysised", "当前文件未分析");
    }

    @RequestMapping("/export")
    public void exportAlarmRange(HttpServletResponse response) throws IOException {
        File file = baseService.exportAlarmRange();
        if(file == null){

        }else{
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
            //setContentType("text/plain; charset=utf-8"); 文本
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("废弃斑马线误报边界.json", "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        }
    }
}
